const app = getApp();

/*
小程序利用canvas实现一键保存图片功能 */
Page({

  /**
   * 页面的初始数据
   */
  data: {
    comeBack:false,//未授权进去设置
    visible:false,
    canvas: {
      width: 636,
      height: 920,
      bg_img: '', //背景图片
      user_img: '', //用户头像
      user_name: '', //用户名称
      icon_img: '', //荣誉图片
      icon_name: '', //荣誉名称
      condition:'',//次数
      ewm_img: '', //二维码图片
    },
    sharePath: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      ['canvas.icon_img']: options.img,
      ['canvas.icon_name']: options.name,
      ['canvas.condition']: options.condition
    })
  },
  onShow() {
    let userInfo = wx.getStorageSync('userInfo');
    if (this.authorizationJudgment()) {
      //没有授权（上面的方法处理）
    }else if (this.data.comeBack){
      this.setData({ comeBack:false})
    }
    if (userInfo != '' && userInfo.avatarUrl != '') {
      this.setData({
        ['canvas.user_img']: userInfo.avatarUrl,
        ['canvas.user_name']: userInfo.nickName
      })
      app._getSettingInfo(res => {
        this.setData({ ['canvas.bg_img']: res.shareBg, ['canvas.ewm_img']: res.miniCode })
        this.drawPic()
      })
    }
  },
  //授权判断
  authorizationJudgment() {
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo == '' || userInfo.avatarUrl == '') {
      wx.showModal({
        title: '提示',
        content: '需要获取您的授权~',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#72B9C3',
        confirmText: '前往授权',
        confirmColor: '#72B9C3',
        success: res => {
          if (res.confirm) {
            this.setData({ comeBack: true })
            wx.navigateTo({
              url: '/pages/get_user_info/index',
            })
          }
        }
      })
      return true
    } else{
      return false
    }
  },
  drawPic() {
    // console.time('getTime');
    if (this.data.sharePath) { //如果已经绘制过了本地保存有图片不需要重新绘制
      this.setData({
        visible: true
      })
      this.triggerEvent('initData')
      return
    }
    wx.showLoading({title: '生成中'})
    let {bg_img,user_img,user_name,icon_img,icon_name,condition,ewm_img} = this.data.canvas
    this.setData({
      imgDraw: {
        width: '636rpx',
        height: '1020rpx',
        views: [
          {
            type: 'image',
            url: bg_img,
            css: {
              top: '0',
              left: '0',
              width: '636rpx',
              height: '1020rpx',
              borderRadius: '24rpx 24rpx 0 0',
            },
          },
          {
            type: 'image',
            url: user_img,
            css: {
              top: '24rpx',
              left: '24rpx',
              width: '88rpx',
              height: '88rpx',
              borderWidth: '3rpx',
              borderColor: '#FFF',
              borderRadius: '44rpx'
            }
          },
          {
            type: 'text',
            text: user_name,
            css: {
              top: '24rpx',
              left: '128rpx',
              fontSize: '32rpx',
              color: '#fff'
            }
          },
          {
            type: 'image',
            url: icon_img,
            css: {
              top: '342rpx',
              left: '180rpx',
              width: '276rpx',
              height: '276rpx'
            }
          },
          {
            type: 'text',
            text: icon_name,
            css: {
              top: '642rpx',
              left: '0rpx',
              width: '638rpx',
              textAlign:'center',
              fontWeight: 'bold',
              fontSize: '32rpx',
              lineHeight: '44rpx',
              color: '#fff'
            }
          },
          {
            type: 'text',
            text: '通过足下赛旅累计报名' + condition+'次',
            css: {
              top: '702rpx',
              left: '0rpx',
              width: '638rpx',
              textAlign: 'center',
              maxLines: 1,
              fontSize: '24rpx',
              color: '#fff'
            }
          },
          {
            type: 'image',
            url: ewm_img,
            css: {
              top: '884rpx',
              left: '24rpx',
              width: '112rpx',
              height: '112rpx',
            }
          }
        ]
      }
    })
  },
  onImgErr(e) {
    wx.hideLoading()
    wx.showToast({
      title: '生成分享图失败，请刷新页面重试'
    })
  },
  onImgOK(e) {
    wx.hideLoading()
    this.setData({
      sharePath: e.detail.path,
      visible: true,
    })
    //通知外部绘制完成，重置isCanDraw为false
    this.triggerEvent('initData');
    // console.timeEnd('getTime');
  },
  //保存至相册
  saveImage: function () {
    if (this.authorizationJudgment()){

    } else {
      this.saveImageToPhotosAlbum(this.data.sharePath)
    }
  },
  saveImageToPhotosAlbum(img){
    let that = this
    wx.saveImageToPhotosAlbum({
      filePath: img,
      success: function (data) {
        wx.showModal({
          title: '图片保存成功',
          content: '图片成功保存到相册了，去发圈噻~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function (res) {
            that.setData({ canvasHidden: true})
          }
        })
      },
      fail: function (err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.showModal({
            title: '提示',
            content: '需要获取权限才能保存到相册',
            success (res) {
              if (res.confirm) {
                    wx.openSetting({
                      success(settingdata) {
                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          wx.showToast({ title: '获取权限成功'})
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                        } else {
                          wx.showModal({
                            title: '提示',
                            content: '没有权限，人家很难给你保存到相册',
                            showCancel: false,
                            confirmText: '好的',
                            confirmColor: '#72B9C3',
                            success: function (res) {
                            }
                          })
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                        }
                      }
                    })
              } else if (res.cancel) {
                // console.log('用户点击取消')
              }
            }
          })
        }
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // onUnload() {
  //   let { user_img,icon_img, ewm_img, bg_img } = this.data.canvas
  //   app.removeFiles(user_img, state => {//用户头像
  //     app.removeFiles(bg_img, state => {//背景图片
  //       app.removeFiles(icon_img, state => {//荣誉图片
  //         app.removeFiles(ewm_img, state => {//二维码

  //         })
  //       })
  //     })
  //   })
    
  // }
})